﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using UI.ParentForm;
using Model;
using UI.Lib;
using System.Collections;
using UI.Lib.Factory;

namespace UI.CommonForm
{
    public partial class FrmCustomOrder : BaseForm
    {
        private string _pageName = ""; //当前页面名称
        private List<TextValuePair> targetSource = null;
        private DataTable dtSorts = null;
        private Hashtable tbSummary = null; //概要表数据
        private string saveCallFuntion = "Sys7a00Manager$SaveData";

        /// <summary>
        /// 左边框的备选项
        /// </summary>
        public List<TextValuePair> TargetSource
        {
            get { return targetSource; }
            set { targetSource = value; }
        }

        public FrmCustomOrder()
        {
            InitializeComponent();
        }

        public FrmCustomOrder(string title, string pageName, List<TextValuePair> lst)
        {
            InitializeComponent();

            //设置页面的标题
            this.Text = string.Format("自定义排序 - [{0}]", title);
            this.targetSource = lst;
            this._pageName = pageName;

            FillUserSort();
            BindTargetBox();
        }

        /// <summary>
        /// 绑定备选框
        /// </summary>
        private void BindTargetBox()
        {
            if (null == targetSource) return;

            DataView view = null;
            TextValuePair pv = null;
            foreach (TextValuePair p in targetSource)
            {
                //使用克隆，保存最原始的列信息
                pv = Components.CommonUtil.GetInstance.Clone(p) as TextValuePair;
                if (pv == null) continue;

                view = new DataView(dtSorts);
                view.RowFilter = string.Format("colname='{0}'", pv.Value); //如果当前的列出现在了用于选择区内，那么不应该出现在左边的选项框中
                if (view.Count > 0) continue;

                this.lstBoxLeft.Items.Add(pv);
            }
        }

        /// <summary>
        /// 填充用户的排序方式在左边框框内
        /// </summary>
        private void FillUserSort()
        {
            dtSorts = UI.Lib.Factory.CommonHelper.Entity.ExecFun("getsortsbyusercode",
                new KeyValuePair<string, object>("@a", Context.Comocde), //公司
                new KeyValuePair<string, object>("@b", Context.LoginName), //用户名
                new KeyValuePair<string, object>("@c", _pageName)); //页面信息

            if (dtSorts == null || 0 == dtSorts.Rows.Count) return;

            this.lstBoxRight.Items.Clear();

            TextValuePair tv = null;
            foreach (DataRow dr in dtSorts.Rows)
            {
                tv = new TextValuePair(string.Format("{0}    {1}",
                    ("A" == dr["sortype"].ToString() ? "↑" : "↓"),
                    dr["headcn"]), Components.Validation.ToString(dr["colname"]));

                this.lstBoxRight.Items.Add(tv);
            }
        }

        /// <summary>
        /// 单个移至左边栏目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnA_Click(object sender, EventArgs e)
        {
            TextValuePair item = this.lstBoxLeft.SelectedItem as TextValuePair;
            if (null == item) return;

            this.lstBoxLeft.Items.Remove(item);
            item.Text = string.Format("↑    {0}", item.Text);

            this.lstBoxRight.Items.Add(item);

            if (this.lstBoxLeft.Items.Count > 0) this.lstBoxLeft.SelectedIndex = 0;
        }

        /// <summary>
        /// 全部移至右边栏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnB_Click(object sender, EventArgs e)
        {
            if (0 == this.lstBoxLeft.Items.Count) return;

            TextValuePair item = null;
            foreach (object i in this.lstBoxLeft.Items)
            {
                item = i as TextValuePair;
                if (item == null) continue;

                item.Text = string.Format("↑    {0}", item.Text);

                this.lstBoxRight.Items.Add(item);
            }

            this.lstBoxLeft.Items.Clear();
            if (this.lstBoxRight.Items.Count > 0) this.lstBoxRight.SelectedIndex = 0;
        }

        private void btnD_Click(object sender, EventArgs e)
        {
            if (0 == this.lstBoxRight.Items.Count) return;

            TextValuePair item = null;
            foreach (object i in this.lstBoxRight.Items)
            {
                item = i as TextValuePair;
                if (item == null) continue;

                item.Text = item.Text.Replace("↑    ", "").Replace("↓    ", "");

                this.lstBoxLeft.Items.Add(item);
            }

            this.lstBoxRight.Items.Clear();

            if (this.lstBoxLeft.Items.Count > 0) this.lstBoxLeft.SelectedIndex = 0;
        }

        private void btnC_Click(object sender, EventArgs e)
        {
            TextValuePair item = this.lstBoxRight.SelectedItem as TextValuePair;
            if (null == item) return;

            this.lstBoxRight.Items.Remove(item);
            item.Text = item.Text.Replace("↑    ", "").Replace("↓    ", "");

            this.lstBoxLeft.Items.Add(item);
        }

        private void lstBoxRight_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (null != e && e.Button != MouseButtons.Left) return;

            TextValuePair item = this.lstBoxRight.SelectedItem as TextValuePair;
            if (null == item) return;

            int i = this.lstBoxRight.FindString(item.Text);

            if (item.Text.StartsWith("↑"))
                item.Text = item.Text.Replace("↑    ", "↓    ");
            else
                item.Text = item.Text.Replace("↓    ", "↑    ");

            this.lstBoxRight.Items.RemoveAt(i);
            this.lstBoxRight.Items.Insert(i, item); //移除，再重新插入，达到字幕更新的效果
            this.lstBoxRight.SelectedIndex = i;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (this.lstBoxRight.Items.Count == 0
                && MessageBox.Show("当前您所选择的排序方式为空，是否继续？", "提示", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                return;
            }

            DataTable dt = new DataTable();
            dt.TableName = "DTLDATA";
            DataColumn dc;
            //添加colName列
            dc = new DataColumn();
            dc.ColumnName = "colname";
            dt.Columns.Add(dc);

            //添加sortype列
            dc = new DataColumn();
            dc.ColumnName = "sorttype";
            dt.Columns.Add(dc);

            //添加orderid列
            dc = new DataColumn();
            dc.ColumnName = "orderid";
            dt.Columns.Add(dc);

            //填充明细数据
            TextValuePair tv;
            for (int j = 0; j < this.lstBoxRight.Items.Count; j++)
            {
                tv = this.lstBoxRight.Items[j] as TextValuePair;
                if (null == tv) continue;

                DataRow dr = dt.NewRow();
                dr["colname"] = tv.Value;
                dr["sorttype"] = tv.Text.StartsWith("↑") ? "A" : "D"; //箭头朝上代表升序
                dr["orderid"] = j.ToString();

                dt.Rows.Add(dr);
            }

            //概要表数据
            FillSummaryData();

            string errmsg = CommonHelper.Entity.SaveDtl(saveCallFuntion,
                Components.StringUtil.Entity.TableToJson(tbSummary),
                "W",
                dt, null); //调用服务器的保存方法

            bool isSuccess = string.IsNullOrEmpty(errmsg); // 是否保存成功
            if (!isSuccess)
            {
                MessageBox.Show(errmsg, "错误提示");
            }
            else
            {
                this.DialogResult = DialogResult.OK;
                this.Close(); //保存成功
            }
        }

        //概要表数据
        void FillSummaryData()
        {
            if (null == tbSummary)
            {
                tbSummary = new Hashtable();
            }
            else
            {
                tbSummary.Clear();
            }

            tbSummary["pageName"] = this._pageName;
            tbSummary["comcode"] = Context.Comocde;
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            //概要表数据
            FillSummaryData();

            string errmsg = CommonHelper.Entity.SaveDtl(saveCallFuntion,
                Components.StringUtil.Entity.TableToJson(tbSummary),
                "R",
                null, null); //调用服务器的保存方法

            bool isSuccess = string.IsNullOrEmpty(errmsg); // 是否保存成功
            if (!isSuccess)
            {
                MessageBox.Show(errmsg, "错误提示");
            }
            else
            {
                this.DialogResult = DialogResult.OK;
                this.Close(); //保存成功
            }
        }

        private void lstBoxRight_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.Up) //Ctrl + Up交换行
            {
                int nowIndex = this.lstBoxRight.SelectedIndex;
                if (nowIndex < 1) return; //第一行不需要交换

                TextValuePair selectedObj = this.lstBoxRight.SelectedItem as TextValuePair;
                if (null == selectedObj) return;

                this.lstBoxRight.Items.RemoveAt(nowIndex);
                this.lstBoxRight.Items.Insert(nowIndex - 1, selectedObj);
                this.lstBoxRight.SelectedIndex = nowIndex;
            }
            else if (e.Control && e.KeyCode == Keys.Down)
            {
                int maxIndex = this.lstBoxRight.Items.Count;
                int nowIndex = this.lstBoxRight.SelectedIndex;
                if (nowIndex == maxIndex - 1) return; //第一行不需要交换

                TextValuePair selectedObj = this.lstBoxRight.SelectedItem as TextValuePair;
                if (null == selectedObj) return;

                this.lstBoxRight.Items.RemoveAt(nowIndex);
                this.lstBoxRight.Items.Insert(nowIndex + 1, selectedObj);
                this.lstBoxRight.SelectedIndex = nowIndex;
            }
            else if (e.KeyCode == Keys.Enter)
            {
                lstBoxRight_MouseDoubleClick(null, null);
            }
        }

        private void FrmCustomOrder_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F8) //F8 做查询
            {
                this.btnOk.PerformClick();
            }
            else if (e.KeyCode == Keys.F9)
            {
                this.btnReset.PerformClick();
            }
            else if (e.KeyCode == Keys.PageUp)
            {
                this.btnClose.PerformClick();
            }
        }
    }
}
